package cn.kgc.springboot.vue.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.kgc.springboot.vue.commons.QueryCondition;
import cn.kgc.springboot.vue.entity.Student;
import cn.kgc.springboot.vue.exception.BusinessException;
import cn.kgc.springboot.vue.mapper.CourseMapper;
import cn.kgc.springboot.vue.mapper.StudentMapper;
import cn.kgc.springboot.vue.response.ResponseResult;
import cn.kgc.springboot.vue.service.StudentService;
import cn.kgc.springboot.vue.vo.StudentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_student】的数据库操作Service实现
* @createDate 2024-12-27 13:41:50
*/
@Service
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>implements StudentService{

    @Resource
    private CourseMapper courseMapper;

    @Override
    public ResponseResult studentPage(QueryCondition<Student> queryCondition) {

        Page<Student> studentPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        String studentNo = queryCondition.getSearchParams().getStudentNo();
        String clazz = queryCondition.getSearchParams().getClazz();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz)
                .orderByDesc(Student::getSchoolYear);
        baseMapper.selectPage(studentPage,lambda);

        List<StudentVO> studentVOS = studentPage.getRecords().stream()
                .map(student -> {
                    StudentVO studentVO = new StudentVO();
                    BeanUtils.copyProperties(student,studentVO);
                    Integer courseId = student.getCourseId();
                    String courseName = courseMapper.selectById(courseId).getCourseName();
                    studentVO.setCourseName(courseName);
                    return studentVO;
                }).collect(Collectors.toList());


        return ResponseResult.success()
                .data("total",studentPage.getTotal())
                .data("tableData",studentVOS);
    }

    @Override
    public ResponseResult inportStudent(MultipartFile file) {

        // 判定文件是否为空
        if (file.isEmpty()){
            return  ResponseResult.fail().message("请选择文件");
        }

        // 创建一个导入参数对象
        ImportParams importParams = new ImportParams();
        // 表头占据的行数
        importParams.setHeadRows(1);
        // 标题占据的行数
        importParams.setTitleRows(1);
        // 解析excel中的数据
        List<Student> students = null;
        try {
            InputStream inputStream = file.getInputStream();
            students= ExcelImportUtil.importExcel(inputStream, Student.class, importParams);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        students.forEach(student -> {
            try {
                baseMapper.insert(student);
            }catch (DuplicateKeyException e){
                throw  new BusinessException("学号"+student.getStudentNo()+"重复");
            }
        });
        return ResponseResult.success();
    }

    @Override
    public void exportStudent(String studentNo,String clazz, HttpServletResponse response) {

        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(StringUtils.isNotBlank(studentNo),Student::getStudentNo,studentNo)
                .eq(StringUtils.isNotBlank(clazz),Student::getClazz,clazz);
        List<Student> students = baseMapper.selectList(lambda);

        // 创建导出参数
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("学生信息表");
        exportParams.setSheetName("学生信息表1");
        // 工作簿对象
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, students);

        try {
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}




